<template>
  <div :style="{height: loginHeight}" class="allBg">
    <div class="header-box">
      <div class="imgBox">
        <img src="/static/images/fhb-logo.png">
        <span class="header-text">首页</span>
      </div>
    </div>
    <div class="login-content">
      <div class="login-window-box">
        <div class="login-box-left">

        </div>
        <div class="login-box-content">
          <!--<el-form ref="loginForm" :model="model" class="login-form" auto-complete="on" label-position="left">-->
          <el-row>
            <div v-if="active == 1">
              <el-form ref="userLoginForm" :model="userLoginForm" class="login-form" auto-complete="on" label-position="left">
                <el-col :span="24">
                  <div class="title-container">
                    <p class="lg-title"><span>登录居家小二</span></p>
                    <p class="title">
                      <a href="javascript:;" :class="{'check-login': active == 1}" @click="active = 1">账号登录</a>
                      <span style="padding: 0px 26px;font-size: 20px;color:#979797"> |</span>
                      <a href="javascript:;" :class="{'check-login': active == 2}" @click="active = 2">验证登录</a>
                    </p>
                  </div>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="userName">
                    <el-input
                      ref="mark"
                      id="getCursor"
                      v-model="userLoginForm.userName"
                      placeholder="请输入手机号/账号"
                      name="username"
                      type="text"
                      auto-complete="off"
                    >
                      <i class="iconfont icon-ren" slot="prefix" style="font-size:12px;"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="margin-top:15px;">
                  <el-form-item prop="userPwd"
                                :rules="[
                        {required: true, message: '密码必须且6到12位', trigger: 'blur', min: 6, max: 12}
                      ]">
                    <el-input type="password" v-model="userLoginForm.userPwd" placeholder="请输入密码" auto-complete="off" @keyup.enter.native="submit">
                      <i class="iconfont icon-mimasuo" slot="prefix" style="font-size:12px;"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-button :loading="loading" class="login-btn" @click.native.prevent="submit">登 录</el-button>
                </el-col>
                <el-col :span="18">
                  <el-form-item style="border:none;">
                    <!--<el-switch v-model="loginForm.remember"></el-switch>-->
                    <el-checkbox v-model="userLoginForm.remember" :class="{'is-checked': checked}" >记住密码</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item style="border:none">
                    <a href="javascript:;" style="color:#FF8800" @click="goFindWeb">忘记密码</a>
                  </el-form-item>
                </el-col>
                <el-col :span="16" :offset="6">
                  <span style="color:#E7EDF1">———— </span><a class="register-text" href="javascript:;" @click="active = 3"> 立即注册 </a><span style="color:#E7EDF1">  ————</span>
                </el-col>
              </el-form>
            </div>
            <div v-if="active == 2">
              <el-form ref="codeLoginForm" :model="codeLoginForm" class="login-form" auto-complete="on" label-position="left">
                <el-col :span="24">
                  <div class="title-container">
                    <p class="lg-title"><span>登录居家小二</span></p>
                    <p class="title">
                      <a href="javascript:;" :class="{'check-login': active == 1}" @click="active = 1">账号登录</a>
                      <span style="padding: 0px 26px;font-size: 20px;color:#979797"> |</span>
                      <a href="javascript:;" :class="{'check-login': active == 2}" @click="active = 2">验证登录</a>
                    </p>
                  </div>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="loginPhone"
                                :rules="[
                      {required: true, message: '请输入手机号码', trigger: 'blur'},
                      { validator: isPhoneAlias, message: '手机号格式有误', trigger: 'blur' }
                    ]">
                    <el-input
                      ref="mark"
                      clearable
                      v-model="codeLoginForm.loginPhone"
                      placeholder="请输入手机号"
                      name="username"
                      type="text"
                      auto-complete="off"
                    >
                      <i class="iconfont icon-ren" slot="prefix" style="font-size:12px;"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="margin-top:15px;">
                  <el-form-item prop="loginCode" :rules="[
              {required: true, message: '验证码必须', trigger: 'blur'}
            ]">
                    <el-input v-model="codeLoginForm.loginCode" @keyup.enter.native="codeLogin" placeholder="请输入验证码">
                      <!--<span class="show-pwd" ><svg-icon icon-class="eye" /></span>-->
                      <i class="iconfont icon-yanzhengma2" slot="prefix" style="font-size:14px;position:relative;top:12px;"></i>
                      <template slot="append">
                        <el-button  @click.prevent="getLoginCode" :disabled="times > 0">{{ verificationCodeText }}</el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-button :loading="loadingCodeLogin" class="login-btn" @click.native.prevent="codeLogin('fhblogin')">登 录</el-button>
                </el-col>
                <el-col :span="18">
                  <el-form-item style="border:none;">
                    <!--<el-switch v-model="loginForm.remember"></el-switch>-->
                    <el-checkbox v-model="codeLoginForm.remember" :class="{'is-checked': checked}" >记住密码</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item style="border:none">
                    <a href="javascript:;" style="color:#FF8800" @click="goFindWeb">忘记密码</a>
                  </el-form-item>
                </el-col>
                <el-col :span="16" :offset="6">
                  <span style="color:#E7EDF1">———— </span><a class="register-text" href="javascript:;" @click="goRegisterWeb"> 立即注册 </a><span style="color:#E7EDF1">  ————</span>
                </el-col>
              </el-form>
            </div>
            <div v-if="active == 3">
              <el-form ref="registerForm" :model="registerForm" class="login-form" auto-complete="on" label-position="left">
                <el-col :span="24">
                  <div class="title-container">
                    <p class="lg-title"><span>注册居家小二</span></p>
                    <p></p>
                  </div>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="registerPhone"
                                :rules="[
                      {required: true, message: '请输入手机号码', trigger: 'blur'},
                      { validator: isPhone, message: '手机号格式有误', trigger: 'blur' }
                    ]">
                    <el-input
                      ref="mark"
                      clearable
                      v-model="registerForm.registerPhone"
                      placeholder="请输入手机号"
                      name="username"
                      type="text"
                      auto-complete="off"
                    >
                      <i class="iconfont icon-ren" slot="prefix" style="font-size:12px;"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="margin-top:10px;margin-bottom:10px;">
                  <el-form-item prop="registerCode" :rules="[
              {required: true, message: '验证码必须', trigger: 'blur'}
            ]">
                    <el-input v-model="registerForm.registerCode" placeholder="请输入6位验证码" clearable>
                      <!--<span class="show-pwd" ><svg-icon icon-class="eye" /></span>-->
                      <i class="iconfont icon-yanzhengma2" slot="prefix" style="font-size:14px;position:relative;top:12px;"></i>
                      <template slot="append">
                        <el-button @click.prevent="getRegisterCode()" :disabled="times3 > 0">{{ verificationCodeText3 }}</el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="registerPwd"
                                :rules="[
                      {required: true, message: '密码必须且6到12位', trigger: 'blur', min: 6, max: 12}
                    ]">
                    <el-input type="password" clearable v-model="registerForm.registerPwd" placeholder="请输入密码" auto-complete="off" @keyup.enter.native="registerLogin">
                      <i class="iconfont icon-mimasuo" slot="prefix" style="font-size:12px;"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-button :loading="loadingRegister" class="login-btn" @click.native.prevent="register('register')">立即注册</el-button>
                </el-col>
                <el-col :span="18">
                  <el-form-item style="border:none;margin-top: 14px">
                    <el-checkbox v-model="registerForm.isAgree" :class="{'is-checked': registerForm.isAgree}" >已同意 <span style="color:#FF8800;font-size:13px;">《居家智享平台使用协议》</span></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="16" :offset="6">
                  <span style="color:#E7EDF1">———— </span><a class="register-text" href="javascript:;" @click="active = 1"> 立即登录 </a><span style="color:#E7EDF1">  ————</span>
                </el-col>
              </el-form>

            </div>
            <div v-if="active == 4">
              <el-form ref="findForm" :model="findForm" class="login-form" auto-complete="on" label-position="left">
                <el-col :span="24">
                  <div class="title-container">
                    <p class="lg-title" style="margin: 25px auto;"><span>找回密码</span></p>
                    <p style="margin: 45px auto;">
                      <el-steps :active="activeStep" align-center>
                        <el-step title="验证身份"></el-step>
                        <el-step title="设置登录密码"></el-step>
                        <el-step title="完成"></el-step>
                      </el-steps>
                    </p>
                  </div>
                </el-col>
                <el-col :span="24">
                  <!--<el-form class="login-form" :model="findModel" ref="findModelForm">-->
                  <el-row>
                    <div v-show="activeStep == 1">
                      <el-col :span="24">
                        <el-form-item prop="findPhone"
                                      :rules="[
                        {required: true, message: '请输入手机号码', trigger: 'blur'},
                        { validator: isPhone, message: '手机号格式有误', trigger: 'blur' }
                      ]">
                          <el-input
                            ref="mark"
                            clearable
                            v-model="findForm.findPhone"
                            placeholder="请输入手机号"
                            name="username"
                            type="text"
                            auto-complete="off"
                          >
                            <i class="iconfont icon-ren" slot="prefix" style="font-size:12px;"></i>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24" style="margin: 15px auto;">
                        <el-form-item prop="findCode" :rules="[
                          {required: true, message: '验证码必须', trigger: 'blur'}
                             ]">
                          <el-input v-model="findForm.findCode" placeholder="请输入6位验证码">
                            <i class="iconfont icon-yanzhengma2" slot="prefix" style="font-size:14px;position:relative;top:12px;"></i>
                            <template slot="append">
                              <el-button @click.prevent="getFindPswCode" :disabled="times4 > 0"><span>{{ verificationCodeText4 }}</span></el-button>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </div>
                    <div v-show="activeStep == 2">
                      <el-col :span="24">
                        <el-form-item prop="findPwd"
                                      :rules="[
                        {required: true, message: '密码必须且6~12位', trigger: 'blur', min: 6, max: 12}
                      ]">
                          <el-input type="password" v-model="findForm.findPwd" auto-complete="off" placeholder="设置密码">
                            <!--<span slot="prefix" style="font-size:12px;">设置密码</span>-->
                            <!--<template slot="prepend"><span style="font-size:12px;">设置密码</span></template>-->
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24" style="margin: 15px auto;">
                        <el-form-item prop="findPwdTwo"
                                      :rules="[
                        {required: true, message: '再次确认必须', trigger: 'blur'},
                        {validator: isSame, otherValue: findForm.findPwd, message: '两次输入的密码不一致', trigger: 'blur'}
                      ]">
                          <el-input type="password" v-model="findForm.findPwdTwo" placeholder="确认密码" auto-complete="off" @keyup.enter.native="submitFindPsw">
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </div>
                    <div v-if="activeStep == 3">
                      <el-col :span="16" :offset="4">
                        <el-form-item style="text-align:center">
                          <p><i class="el-icon-success m--font-success" style="font-size: 80px;color:#57D092"></i></p>
                          <p>找回成功</p>
                        </el-form-item>
                      </el-col>
                    </div>
                    <div v-if="activeStep == 4">
                      <el-col :span="16" :offset="4">
                        <el-form-item style="text-align:center">
                          <p><i class="el-icon-error m--font-error" style="font-size: 80px;color:#57D092"></i></p>
                          <p>找回失败</p>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-button class="btn-block btn-lg"  type="primary" style="width:100%" @click.native.prevent="active = 1">
                          返回登录
                        </el-button>
                      </el-col>
                    </div>
                    <el-col :span="24" v-if="activeStep != 4">
                      <el-button class="btn-block btn-lg" :loading="loading" type="primary" style="width:100%" @click.native.prevent="submit">
                        {{ activeStep == 3 ? '立即登录' : '下一步' }}
                      </el-button>
                    </el-col>
                    <el-col :span="18" :offset="4" style="margin-top:10px;" v-if="activeStep == 1">
                      <p style="text-align:center;font-size:14px;font-weight:400;color:#333333">
                        <span style="cursor:pointer;margin-right:8px;" @click="active = 1">立即登录 </span>  | <span style="cursor:pointer;margin-left:5px;" @click="goRegisterWeb"> 立即注册</span>
                      </p>
                    </el-col>
                  </el-row>
                  <!--</el-form>-->
                </el-col>
              </el-form>
            </div>
            <div v-if="active == 5">
              <el-form ref="businessForm" :model="businessForm" class="login-form" auto-complete="on" label-position="left">
                <el-col :span="24" style="margin: 20px auto;">
                  <div class="title-container">
                    <p class="lg-title"><span>完善商家资料</span></p>
                    <p></p>
                  </div>
                </el-col>
                <el-col :span="24" style="margin: 20px auto;">
                  <el-form-item prop="businessName"
                                :rules="[
                      {required: true, message: '请填写商家名称', trigger: 'blur'}
                    ]">
                    <el-input
                      ref="mark"
                      clearable
                      v-model="businessForm.businessName"
                      placeholder="请填写商家名称"
                      name="username"
                      type="text"
                      auto-complete="off"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="margin: 20px auto;">
                  <el-form-item prop="DAddress" :rules="[
                    { required: true, message: '请选择所在地区', type: 'array', length: 3, trigger: 'change' },
                  ]">
                    <!--<cascade-address level="3" v-model="model.address" placeholder="请选择省市区" style="width: 100%"></cascade-address>-->
                    <cascade-address v-model="businessForm.DAddress" :level="3" style="width: 100%" placeholder="所在地区（省市区）"></cascade-address>
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="margin-bottom: 40px;">
                  <el-button :loading="businessLoading" class="login-btn" @click.native.prevent="goIndex">立即体验</el-button>
                </el-col>
              </el-form>
            </div>
            <!--<el-col :span="16" :offset="6" v-show="active == 1 || active == 2">-->
            <!--<span style="color:#E7EDF1">———— </span><a class="register-text" href="javascript:;" @click="active = 3"> 立即注册 </a><span style="color:#E7EDF1">  ————</span>-->
            <!--</el-col>-->
            <!--<el-col :span="16" :offset="6" v-if="active == 3">-->
            <!--<span style="color:#E7EDF1">———— </span><a class="register-text" href="javascript:;" @click="active = 1"> 立即登录 </a><span style="color:#E7EDF1">  ————</span>-->
            <!--</el-col>-->
          </el-row>

          <!--</el-form>-->
        </div>
      </div>

    </div>
    <div class="foot-box">
      <div class="foot-text"><span>———— 四川居家智享信息技术有限公司 ————</span></div>
    </div>
  </div>
</template>

<script>
import {isPhone, isSame, isPhoneAlias} from '@/utils/validate'
import {isPhoneUtil} from '@/utils/validatorUtil'
// import { isvalidUsername, isPhone } from '@/utils/validate'
import {alert, dotData, confirm, copy} from '@/utils'
import {setOperationList, setUserInfoData} from '@/utils/auth.js'
// import TimeReduce from '@/utils/TimeReduce'
export default {
  name: 'Login',
  data() {
    return {
      loginHeight: '',
      projectType: process.env.projectType,
      active: 1, // 默认 为账号登录1,验证登录2，注册3，忘记密码4
      verificationCodeText: '获取验证码',
      verificationCodeText3: '获取验证码',
      verificationCodeText4: '获取验证码',
      times: 0, // 验证登录
      times3: 0, // 注册
      times4: 0, // 找回
      config: {
        times: 60, // 验证登录
        times3: 60, // 注册
        times4: 60 // 找回
      },
      checked: false,
      userLoginForm: { // 账号登录
        userName: '',
        userPwd: '',
        remember: false
      },
      codeLoginForm: { // 验证码登录
        loginPhone: '',
        loginCode: '',
        remember: false
      },
      registerForm: {
        registerPhone: '',
        registerCode: '',
        registerPwd: '',
        isAgree: false // 默认没有同意协议
      },
      findForm: {
        findPhone: '',
        findCode: '',
        findPwd: '',
        findPwdTwo: ''
      },
      businessForm: {
        businessName: '', // 商家资料完善
        DAddress: []
      },
      activeStep: 1,
      loginUser: {},
      businessId: '',
      businessLoading: false,
      loadingRegister: false,
      loadingCodeLogin: false,
      loading: false,
      showDialog: false,
      redirect: undefined
    }
  },
  watch: {
    // 切换账号登和验证登后 清空表单
    active(val, oldVal) {
      this.$nextTick(_ => {
        this.clearForms()
      })
      this.loading = false
    },
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }

  },
  mounted() {
    this.loginHeight = document.documentElement.clientHeight + 'px'
    document.getElementById('getCursor').focus() // 默认光标的位置
  },
  created() {
    // this.$nextTick(_ => {
    //   this.$refs.mark.$el.querySelector('input').focus()
    // })
    // window.addEventListener('hashchange', this.afterQRScan)
  },
  methods: {
    isSame,
    isPhone,
    isPhoneAlias,
    // 验证码登录 发送验证码,判断授权否
    getLoginCode() {
      if (this.codeLoginForm.loginPhone) {
        if (!isPhoneUtil(this.codeLoginForm.loginPhone)) {
          alert(`手机号(${this.codeLoginForm.loginPhone})格式不正确`)
          return
        }
        this.$ajax.get('/ms-common-user/user/sendSms', {
          phone: this.codeLoginForm.loginPhone,
          actionId: 'login'
        }).then(response => {
          const status = dotData(response, 'data.status')
          // 若已授权，则直接登录
          if (status === 'error') {
            const firstAuthCode = dotData(response, 'data.firstAuthCode')
            let statusText = this.statusText(firstAuthCode)
            let message = `<P><img src="/static/images/faHuoBao/xiaoer.png" style="width: 60px;height: 60px;border-radius: 50%!important;" alt=""><P>
                            <p class="statusTips">你已通过${statusText}注册居家小二通行证，</p><p>你可以直接登录</p>`
            this.$confirm(message, '温馨提示', {
              confirmButtonText: '前往登录',
              showCancelButton: false,
              dangerouslyUseHTMLString: true,
              confirmButtonClass: 'loginTipsbutton',
              center: true
            }).then(_ => {
              this.active = 1
            })
          } else if (status === 'success') {
            this.times = this.config.times
            this.timeReduce()
          }
          if (response.success) {
            this.times = this.config.times
            this.timeReduce()
          }
        })
      } else {
        alert('请输入手机号')
      }
    },
    // 验证码登录 倒计时
    timeReduce() {
      if (this.times > 0) {
        this.verificationCodeText = this.times + 's后重新获取'
        setTimeout(this.timeReduce, 1000)
        this.times -= 1
      } else {
        this.verificationCodeText = '获取验证码'
      }
    },
    // 注册：发送验证码+倒计时
    getRegisterCode() {
      if (this.registerForm.registerPhone) {
        let data = {
          phone: this.registerForm.registerPhone,
          actionId: 'register'
        }
        // 请求验证码
        this.$ajax.get('/ms-common-user/user/sendFhbSms', data).then(response => {
          // 之后 取返回值status判断是否授权
          const status = dotData(response, 'data.status')
          // 如果已存在该账号未授权，请直接去登录，不用注册
          if (status === 'error') {
            const firstAuthCode = dotData(response, 'data.firstAuthCode')
            let statusText = this.statusText(firstAuthCode)
            let message = `<P><img src="/static/images/faHuoBao/xiaoer.png" style="width: 60px;height: 60px;border-radius: 50%!important;" alt=""><P>
                            <p class="statusTips">你已通过${statusText}注册居家小二通行证，</p><p>你可以直接登录</p>`
            this.$confirm(message, '温馨提示', {
              confirmButtonText: '前往登录',
              showCancelButton: false,
              dangerouslyUseHTMLString: true,
              confirmButtonClass: 'loginTipsbutton',
              center: true
            }).then(_ => {
              this.active = 1 // 前往登录
            })
          } else if (status === 'success') { // 已授权
            this.times3 = this.config.times3
            this.timeReduce3()
          }
          if (response.success) {
            this.times3 = this.config.times3
            this.timeReduce3()
          }
        })
      } else {
        alert('请输入手机号')
      }
    },
    // 注册-倒计时
    timeReduce3() {
      if (this.times3 > 0) {
        this.verificationCodeText3 = this.times3 + 's后重新获取'
        setTimeout(this.timeReduce3, 1000)
        this.times3 -= 1
      } else {
        this.verificationCodeText3 = '获取验证码'
      }
    },
    // 注册账号来源
    statusText(status) {
      switch (status) {
        case 'storeWeb' : return '居家小二SaaS云'
        case 'fhbBack' : return '居家小二运营后台'
        case 'platWorker' : return '居家小二师傅端'
        default : return ''
      }
    },
    // 找密码 发送验证码+判断是否授权
    getFindPswCode() {
      if (this.findForm.findPhone) {
        this.times4 = this.config.times4
        this.timeReduce4()
        this.$ajax.get('/ms-common-user/user/sendSms', {
          phone: this.findForm.findPhone,
          actionId: 'resetPassword'
        }).then(result => {
          const status = dotData(result, 'data.status')
          if (status === 'error') {
            this.$confirm('该账号尚未授权，不能进行此操作', '温馨提示', {
              confirmButtonText: '确定',
              showCancelButton: false,
              dangerouslyUseHTMLString: true,
              confirmButtonClass: 'loginTipsbutton',
              center: true
            }).then(_ => {
              this.active = 1
            })
          }
        })
      } else {
        alert('请输入手机号')
      }
    },
    // 找密码 倒计时
    timeReduce4() {
      if (this.times4 > 0) {
        this.verificationCodeText4 = this.times4 + 's后重新获取'
        setTimeout(this.timeReduce4, 1000)
        this.times4 -= 1
      } else {
        this.verificationCodeText4 = '获取验证码'
      }
    },
    // 账号登录+商家资料完善+商家授权
    userLoginSubmit() {
      this.$refs.userLoginForm.validate(result => {
        if (!result) {
          return
        }
        let postData = {
          phone: this.userLoginForm.userName,
          pwd: this.userLoginForm.userPwd,
          projectType: this.projectType
        }
        this.loading = true
        this.$ajax.post('/ms-common-user/user/login', postData).then(response => {
          const status = dotData(response, 'data.status')
          if (status === 'success') {
            this.loginUser = response.data
            this.token = dotData(response, 'data.token')
            this.user = dotData(response, 'data.user')
            const userId = dotData(response, 'data.user.id')
            // 登录成功后，检查是否完善商家资料
            this.checkBusiness(userId, this.token).then(resp => {
              if (dotData(resp, 'data.isUpdateBusiness')) { // 若true:未完善，则跳去填写商家表单
                this.active = 5
              } else { // 若已完善过商家资料，则登入
                let operationList = dotData(response, 'data.operation-list')
                if (Array.isArray(operationList)) {
                  // login.setOperationList(operationList)
                  setOperationList(operationList)
                }
                // 登入，传数据给vueX
                this.$store.dispatch('LoginUser', this.loginUser).then(_ => {
                  window.location.href = '/'
                }).catch(e => {
                  alert(e.message)
                })
              }
            })
          } else if (status === 'error') { // 若商家未授权(去授权==给其注册fhb)
            const firstAuthCode = dotData(response, 'data.firstAuthCode')
            let statusText = this.statusText(firstAuthCode)
            let message = `<P><img src="/static/images/faHuoBao/xiaoer.png" style="width: 60px;height: 60px;border-radius: 50%!important;" alt=""><P>
                            <p class="statusTips">你正在使用${statusText}通行证授权登录居家小二商家端</p>`
            confirm(message, '居家小二通行证授权', {
              confirmButtonLoading: true,
              dangerouslyUseHTMLString: true,
              showCancelButton: false,
              confirmButtonText: '登录并完善资料',
              confirmButtonClass: 'loginTipsbutton',
              confirmCallBack: ({confirmButtonLoadingClose, close}) => {
                this.$ajax.post('/ms-fahuobao-user/OutGoodsUser/register', {phone: this.userLoginForm.userName}).then(response => {
                  if (response.success) {
                    this.token = dotData(response, 'data.token')
                    this.loginUser.token = this.token // 未授权时需要更换里面的token
                    this.user = dotData(response, 'data.user')
                    const userId = dotData(response, 'data.user.id')
                    close()
                    this.checkBusiness(userId, this.token).then(resp => {
                      if (dotData(resp, 'data.isUpdateBusiness')) {
                        this.active = 5
                      } else {
                        this.$store.dispatch('LoginUser', this.loginUser).then(_ => {
                          window.location.href = '/'
                        }).catch(e => {
                          alert(e.message)
                        })
                      }
                    })
                  }
                  confirmButtonLoadingClose()
                }).catch(_ => {
                  confirmButtonLoadingClose()
                })
              }
            })
          }
        }).finally(_ => {
          this.loading = false
        })
      })
    },
    // 检查：是否完善商家信息(登录成功后的userId来请求接口)
    checkBusiness(id, token) {
      return new Promise((resolve, reject) => {
        // httpGetResponse('/ms-fahuobao-user-temporary/OutGoodsUser/is-update-business', {id: id}, {headers: {token}}).then(response => {
        this.$ajax.get('/ms-fahuobao-user/OutGoodsUser/is-update-business', {id: id}, {headers: {token}}).then(response => {
          this.businessId = dotData(response, 'data.id')
          this.businessForm.businessName = dotData(response, 'data.name') || ''
          if (response.success) {
            resolve(response) // 若请求成功，将结果返给 调用者
          }
        })
      })
    },
    // 切换 即清空各个表单
    clearForms() {
      if (this.$refs.userLoginForm) {
        this.$refs.userLoginForm.resetFields()
      }
      if (this.$refs.codeLoginForm) {
        this.$refs.codeLoginForm.resetFields()
      }
      if (this.$refs.registerForm) {
        this.$refs.registerForm.resetFields()
      }
      if (this.$refs.findForm) {
        this.findForm.findPhone = ''
        this.findForm.findCode = ''
        this.findForm.findPwd = ''
        this.findForm.findPwdTwo = ''
      }
      if (this.$refs.businessForm) {
        this.$refs.businessForm.resetFields()
        this.businessForm.DAddress = []
      }
    },
    // 去 注册
    goRegisterWeb() {
      this.active = 3
      this.registerForm.registerPwd = ''
      if (this.$refs.registerForm) {
        this.$refs.registerForm.resetFields()
      }
    },
    // 去 找回密码
    goFindWeb() {
      this.active = 4
      this.activeStep = 1
      this.$nextTick(_ => {
        if (this.$refs.findForm) {
          // this.$refs.findForm.resetFields()
          this.findForm.findPhone = ''
          this.findForm.findCode = ''
          this.findForm.findPwd = ''
          this.findForm.findPwdTwo = ''
        }
      })
    },
    // 集中管理 分发各个‘提交’按钮
    submit() {
      if (this.active === 1) { // 账号登录
        this.userLoginSubmit()
      } else if (this.active === 2) { // 验证码登录
        this.codeLogin()
      } else if (this.active === 3) { // 注册
        this.register('register')
      } else if (this.active === 4) { // 找回密码
        if (this.activeStep === 1) { // 验证code
          if (this.findForm.findPhone) {
            if (this.findForm.findCode) {
              this.checkCode('resetPassword').then(response => {
                if (response.success) {
                  this.activeStep = 2
                  // this.backTwoCode = dotData(response, 'data.message') 返回的二次验证码
                }
              })
            } else {
              alert('请输入验证码')
            }
          } else {
            alert('请输入手机号')
          }
        }
        if (this.activeStep === 2) { // 提交新密码
          this.submitFindPsw()
        }
        if (this.activeStep === 3) { // 找回成功后的 去登录按钮
          this.active = 1
        }
      }
    },
    // 提交 找回密码
    submitFindPsw() {
      this.$refs.findForm.validate(result => {
        if (!result) {
          return
        }
        let postData = {
          phone: this.findForm.findPhone,
          pwd: this.findForm.findPwd
        }
        this.$ajax.post('/ms-common-user/user/savePwd', postData).then(data => {
          const success = dotData(data, 'success')
          if (success) {
            console.log('新密码设置成功')
            this.activeStep = 3
          } else {
            console.log('找回失败')
            this.activeStep = 4
          }
        })
      })
    },
    // 验证码登录 + 完善商家资料 + 商家授权
    codeLogin() {
      this.$refs.codeLoginForm.validate(result => {
        if (!result) {
          return
        }
        let userDat = {
          phone: this.codeLoginForm.loginPhone,
          verifyCode: this.codeLoginForm.loginCode,
          projectType: this.projectType
        }
        this.loadingCodeLogin = true
        this.$ajax.post('/ms-common-user/user/login', userDat).then(response => {
          const status = dotData(response, 'data.status')
          if (status === 'success') {
            this.loginUser = response.data
            this.token = dotData(response, 'data.token')
            this.user = dotData(response, 'data.user')
            const userId = dotData(response, 'data.user.id')
            // 登录成功后，检查是否完善商家资料
            this.checkBusiness(userId, this.token).then(resp => {
              this.loadingCodeLogin = false
              if (dotData(resp, 'data.isUpdateBusiness')) {
                this.active = 5
              } else {
                let operationList = dotData(response, 'data.operation-list')
                if (Array.isArray(operationList)) {
                  // login.setOperationList(operationList)
                  setOperationList(operationList)
                }
                // 登入，传数据给vueX
                this.$store.dispatch('LoginUser', this.loginUser).then(_ => {
                  window.location.href = '/'
                }).catch(e => {
                  alert(e.message)
                })
              }
            })
          } else if (status === 'error') { // 若商家未授权(去授权==给其注册fhb)
            this.loadingCodeLogin = false
            const firstAuthCode = dotData(response, 'data.firstAuthCode')
            let statusText = this.statusText(firstAuthCode)
            let message = `<P class=""><img src="/static/images/faHuoBao/xiaoer.png" style="width: 60px;height: 60px;border-radius: 50%!important;" alt=""><P>
                            <p class="statusTips">你正在使用${statusText}通行证授权登录居家小二商家端</p>`
            confirm(message, '居家小二通行证授权', {
              confirmButtonLoading: true,
              dangerouslyUseHTMLString: true,
              showCancelButton: false,
              confirmButtonText: '登录并完善资料',
              confirmButtonClass: 'loginTipsbutton',
              confirmCallBack: ({confirmButtonLoadingClose, close}) => {
                this.$ajax.post('/ms-fahuobao-user/OutGoodsUser/register', {phone: this.codeLoginForm.loginPhone}).then(response => {
                  if (response.success) {
                    this.loginUser.token = this.token // 未授权时需要更换里面的token
                    this.token = dotData(response, 'data.token')
                    this.user = dotData(response, 'data.user')
                    const userId = dotData(response, 'data.user.id')
                    close()
                    this.checkBusiness(userId, this.token).then(resp => {
                      if (dotData(resp, 'data.isUpdateBusiness')) {
                        this.active = 5
                      } else { // 登入
                        this.$store.dispatch('LoginUser', this.loginUser).then(_ => {
                          window.location.href = '/'
                        }).catch(e => {
                          alert(e.message)
                        })
                      }
                    })
                  }
                  confirmButtonLoadingClose()
                }).catch(_ => {
                  confirmButtonLoadingClose()
                })
              }
            })
          }
        }).finally(_ => {
          this.loadingCodeLogin = false
        })
      })
    },
    // 提交商家资料
    goIndex() {
      this.$refs.businessForm.validate().then((result) => {
        // console.log('businessId222222', this.businessId)
        if (result) {
          let copyModel = copy(this.businessForm, true)
          let postObj = {
            id: this.businessId,
            businessName: dotData(this.businessForm, 'businessName'),
            provinceNo: copyModel.DAddress[0],
            cityNo: copyModel.DAddress[1],
            districtNo: copyModel.DAddress[2]
          }
          console.log('商家资料提交的postObj', postObj)
          this.businessLoading = true
          this.$ajax.post('/ms-fahuobao-user/OutGoodsUser/updateBusiness', postObj, {}, {headers: {token: this.token}}).then(response => {
            this.businessLoading = false
            // 取出返回的用户name和token
            let name = dotData(response, 'data.user.name')
            let token = dotData(response, 'data.token')
            setUserInfoData(name, token) // 更新右上角的name名
            if (dotData(response, 'success')) {
              this.$confirm('资料已完善', '提示', {
                type: 'success',
                center: true,
                confirmButtonText: '确定',
                showCancelButton: false,
                closeOnClickModal: false
              }).then(_ => {
                this.$store.dispatch('LoginUser', this.loginUser).then(_ => {
                  window.location.href = '/'
                }).catch(e => {
                  alert(e.message)
                })
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 改-通用：检验验证码 正确否,并返回二次验证码
    checkCode(markType) {
      return new Promise((resolve, reject) => {
        console.log('now--actionId----', markType)
        let checkData = {}
        if (markType === 'register') {
          checkData = {
            actionId: markType,
            phone: this.registerForm.registerPhone,
            code: this.registerForm.registerCode
          }
        }
        if (markType === 'resetPassword') {
          checkData = {
            actionId: markType,
            phone: this.findForm.findPhone,
            code: this.findForm.findCode
          }
        }
        this.$ajax.get('/ms-common-user/user/check-verification-code', checkData).then(response => {
          console.log(response, 'response.success', response.data)
          if (response.success) { // 若验证码正确，则接着往下执行 成功回调
            resolve(response)
          }
        })
      })
    },
    // 注册
    register(mark) {
      this.$refs.registerForm.validate(result => {
        if (!result) {
          return
        }
        if (!this.registerForm.isAgree) {
          alert('注：同意《居家智享平台使用协议》后方可注册')
          return
        }
        // 验证码OK后取出返回的二次验证码 一并提交
        this.checkCode(mark).then(response => {
          let userData = {
            phone: this.registerForm.registerPhone,
            pwd: this.registerForm.registerPwd,
            core: dotData(response, 'data.key') // checkCode接口返回的二次验证码
          }
          this.$ajax.post('/ms-fahuobao-user/OutGoodsUser/register', userData).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              this.loginUser = response.data
              this.token = dotData(response, 'data.token')
              this.user = dotData(response, 'data.user')
              this.businessId = dotData(response, 'data.user.businessId')
              // 注册提交信息后 鼓捣去完善 商家资料
              this.active = 5
              // 暂时屏蔽
              // let interval = setInterval(() => { // 5s倒计时 开始
              //   if ((this.timeNum--) === 0) {
              //     this.timeNum = 0
              //     clearInterval(interval) // 5s倒计时 结束
              //     login.login({token, user}) // 获取到后端返回的token 后 自动登录
              //   }
              // }, 1000)
            } else {
              // show注册失败 页面
            }
          })
        })
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  $bg:#fff;
  $dark_gray: #63717b;
  $light_gray:#409EFF;
  $light_blue:#409EFF;
  $border_gray:#dadada;
  $cursor: #000;

  .check-login {
    color:#FF8800
  }
  .allBg {
    background: url('/static/images/bgColor.png') no-repeat; /*整个背景图*/
    background-size: 100% 100%;
    /*-moz-background-size: cover;*/
    /*-webkit-background-size: cover;*/
    /*background-size: cover;*/
    -moz-background-size: cover;
    -webkit-background-size: cover;
  }
  .header-box {
    width: 100%;
    height: 60px;
    background-color: white;
    text-align: center;
    position:relative;
    .imgBox {
      position:absolute;
      left:10%;
      top: 10px;
      height: 48px;
      width: 200px;
    }
    .header-text{
      width:50px;
      position:absolute;
      left:106%;
      top: 16px;
      font-size:14px;
      font-family:PingFangSC-Regular;
      font-weight:400;
    }
  }
  .login-content {
    /*position: relative;*/
    height: 100%;
    width: 100%;
    background: url('/static/images/bgColor.png') no-repeat; /*整个背景图*/
    background-size: cover;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    /*登录框*/
    .login-window-box {
      /*position:relative;*/
      /*right:1%;*/
      /*top:10%;*/
      /*width:437px;*/
      width:1000px;
      height:466px;
      /*暂时屏蔽*/
      margin:10% auto;
    }
    .login-box-left{
      width:437px;
      height:466px;
      float: left;
      background: url('/static/images/left_bg 2.png') no-repeat;
    }
    .login-box-content {
      float: right;
      width:437px;
      height:466px;
    }
    .login-form {
      position: absolute;
      width:437px; /*form宽度*/
      max-width: 100%;
      height:454px;
      padding: 2px 35px 15px 35px;
      background-color: white;
    }
    .login-btn {
      width:100%;
      margin-top:13px;
      background-color: rgb(255, 136, 0);color:white;
    }
    /*.tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;
      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }*/
    .title-container { /*登录标题默认大小 颜色*/
      position: relative;
      .lg-title {
        text-align: center;
        width:146px;
        margin:20px auto;
        height:33px;
        font-size:24px;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(51,51,51,1);
        line-height:33px;
      }
      /*登录 小标题*/
      .title {
        font-size: 18px;
        /*标题文字颜色*/
        color: #979797;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: 400;
        font-family:PingFangSC-Regular;
        font-weight:400;
        /*color:rgba(255,136,0,1);*/
        line-height:25px;
      }
      /*.set-language {
        color: #fff;
        position: absolute;
        top: 5px;
        right: 0px;
      }*/
    }
    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .thirdparty-button {
      position: absolute;
      right: 35px;
      bottom: 28px;
    }
    .register-text {
      width:56px;
      height:20px;
      font-size:14px;
      font-family:PingFangSC-Regular;
      font-weight:400;
      color:rgba(51,51,51,1);
      line-height:18px;
      text-decoration: none;
    }
  }
  .foot-box {
    position:fixed;
    left:0;
    bottom:0;
    width: 100%;
    height: 50px;
    background-color: white;
    z-index: 999;
    text-align: center;
    .foot-text {
      width:380px;
      height:20px;
      margin: 16px auto;
      color:rgba(171,185,203,1);
      font-size:14px;
      font-family:PingFangSC-Light;
    }
  }
</style>
